package com.plr.dump;

import java.io.ByteArrayInputStream;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map.Entry;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.google.common.base.Joiner;

public class DHandler extends DefaultHandler {

	LinkedList<Robert> stack = new LinkedList<>();

	static Joiner slash = Joiner.on('/');

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

		printAttr();

		Robert r = new Robert();

		r.setNode(qName); 
		r.setAttributes(attributes);

		System.out.println();
		
//		printAttr();
		
		stack.add(r);

		System.out.print("/" + slash.join(stack));

	}

	public void endElement(String uri, String localName, String qName) throws SAXException {

		if (stack.getLast().getNode().equals("CustomData")) {
			System.out.println();

			SAXParser saxParser;
			try {

				SAXParserFactory factory = SAXParserFactory.newInstance();
				saxParser = factory.newSAXParser();

				DefaultHandler handler = new DHandler();

				saxParser.parse(new ByteArrayInputStream(customData.toString().getBytes()), handler);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// saxParser.parse("CustomData.xml", handler);
		}

		printAttr();

		// System.out.println();
		stack.removeLast();
		
		printAttr();
	}

	private void printAttr() {

		if (stack.isEmpty())
			return;

		Robert robert = stack.getLast();

		if (robert.isAttrprinted()) {
			return;
		}
		
		LinkedHashMap<String, String> attributes = robert.getAttr();

		if (attributes.size() > 0) {
			System.out.println();
		}
		
		for ( Entry<String, String> en : attributes.entrySet()) {

			// stack.add("@" + attributes.getLocalName(i));
			System.out.print("/" + slash.join(stack) + "@" + en.getKey());
			System.out.print("\t");
			System.out.println(en.getValue());
			// stack.removeLast();
		}
		robert.setAttrprinted(true); 
	}

	public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {
		String s = new String(ch, start, length);
		s = s.trim();

		if (!s.isEmpty()) {
			s = s.replaceAll("\\s+", " ");
			System.err.print("\t");
			System.err.println(s);
		}

	}

	StringBuffer customData = new StringBuffer();

	@Override
	public void characters(char ch[], int start, int length) throws SAXException {
		String s = new String(ch, start, length);
		s = s.trim();

		if (stack.getLast().getNode().equals("CustomData")) {
			customData.append(s);
		} else if (!s.isEmpty()) {
			s = s.replaceAll("\\s+", " ");
			System.out.print("\t");
			System.out.println(s);
		}

	}

	
}
